using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace ProceduralCity
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game : Microsoft.Xna.Framework.Game
    {
        public static GraphicsDeviceManager graphics;

        BasicEffect buildingEffect;
        SpriteBatch spriteBatch;
        FPSCamera camera;
        Input input;

        static bool exit = false;

        City city;

        public Game()
        {
            if (graphics == null)
                graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";
        }

        public static void RequestExit()
        {
            exit = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            int numWide = 5;
            int numDeep = 5;
            float gap = 160;

            Vector3 maxBuildingSize = new Vector3(400, 800, 400);
            Vector3 minBuildingSize = new Vector3(maxBuildingSize.X * 0.6f, maxBuildingSize.Y * 0.2f, maxBuildingSize.Z * 0.6f);
            Vector3 citySize = (maxBuildingSize + new Vector3(gap, 0, gap)) * new Vector3(numWide, 1, numDeep);
            Vector3 cityCenter = citySize / 2;

            camera = new FPSCamera(graphics.GraphicsDevice, 800);
            camera.Position = new Vector3(
                0.5f * citySize.X,
                1.0f * citySize.Y,
                (numDeep + 2) * (maxBuildingSize.Z + gap)
            );
            //camera.LookAt(camera.Position + Vector3.Forward);
            camera.LookAt(cityCenter);

            input = new Input(camera);
            city = new City(graphics.GraphicsDevice, numWide, numDeep, gap, minBuildingSize, maxBuildingSize);

            ConfigureGraphics();
            ConfigureBuildingEffect();
            base.Initialize();
        }

        private void ConfigureGraphics()
        {
            // TODO: Properly enable anti-aliasing: http://stackoverflow.com/questions/1784466/xna-antialias-question
            graphics.PreferMultiSampling = true;

            SamplerState samplerState = new SamplerState();
            samplerState.Filter = TextureFilter.Anisotropic;
            samplerState.MaxAnisotropy = 16;
            graphics.GraphicsDevice.SamplerStates[0] = samplerState;
        }

        private void ConfigureBuildingEffect()
        {
            buildingEffect = new BasicEffect(graphics.GraphicsDevice);
            buildingEffect.TextureEnabled = true;
            buildingEffect.EnableDefaultLighting();
            buildingEffect.AmbientLightColor = Color.WhiteSmoke.ToVector3();
            buildingEffect.FogEnabled = true;
            buildingEffect.FogColor = Color.Gray.ToVector3();
            buildingEffect.FogStart = camera.ViewDistance / 4;
            buildingEffect.FogEnd = camera.ViewDistance;
            buildingEffect.PreferPerPixelLighting = true;
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(graphics.GraphicsDevice);

            // Note: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // Note: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (exit)
                Exit();

            float deltaSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
            input.Update(deltaSeconds);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            graphics.GraphicsDevice.Clear(Color.Gray);

            buildingEffect.World = Matrix.Identity;
            buildingEffect.View = camera.View;
            buildingEffect.Projection = camera.Projection;
            city.Draw(graphics.GraphicsDevice, buildingEffect, buildingEffect);

            base.Draw(gameTime);
        }
    }
}
